<?php


namespace App\Http\Middleware;


use Closure;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

/**
 * 返回数据结构转驼峰
 * Class ResponseTransFormMiddleware
 * @package App\Http\Middleware
 */
class ResponseTransFormMiddleware
{
    /**
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $expectPath = [
            '/api/v1/pay/refundCallback',
            '/api/v1/pay/callback',
            '/api/v1/pay/notify'
        ];
        if (in_array($request->getPathInfo(), $expectPath)) {
            return $response;
        }
        return response()->json($this->changeHump($response->original));
    }


    /**
     * 转换驼峰(只转key)
     * @param $params
     * @return array
     */
    public function changeHump($params)
    {
        if (is_array($params)) {
            foreach ($params as $key=>$value){
                if ($value instanceof \Illuminate\Database\Eloquent\Model) {
                    $value = $value->toArray();
                }
                if(is_integer($value) && strlen($value) >= 16){
                    $value = (string) $value;
                }
                unset($params[$key]);
                $params[$this->convertUnderline($key)] = is_array($value)?$this->changeHump($value):$value;
            }
        }
        return $params;
    }

    /**
     * @param $str
     * @return string|string[]|null
     */
    public function convertUnderline($str)
    {
        return  preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {return strtoupper($matches[2]);}, $str);
    }
}
